<?php

class FileAttachment extends Eloquent {

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'file_attachment';


	/**
	 * @return mixed
	 */
	protected $primaryKey = 'id';
		
	/**
	 * 软删除
	 * 
	 * @var boolean
	 */
	protected $softDelete = true;
	
	const ITEM_TYPE_ARTICLE = 'articles';
	const ITEM_TYPE_POST = 'posts';
	
	/**
	 * 保存附件
	 * 
	 * @param string $type
	 * @param string $file_name
	 * @param string $src
	 * 
	 * @return FileAttachment
	 */
    public static function saveAttachment($type, $file_name, $src) {
        $attachment = new FileAttachment();
        $attachment->type = $type;
        $attachment->file_name = $file_name;
        $attachment->src = $src;
        $attachment->save();
        return $attachment;
    }
    
    /**
     * 把附件和item相关联
     * 
     * @param int $attachment_id
     * @param int $item_id
     * @param string $item_type
     */
    public static function bindAttachmentWithItem($attachment_id, $item_id, $item_type) {
        DB::transaction(function() use($attachment_id, $item_id, $item_type){
            // delete other file attachments originally bound to this item
            $attachments = FileAttachment::where('item_id', $item_id)->get();
            foreach($attachments as $attachment) {
                $attachment->delete();
            }
            
            // bind this item to the file attachment
            $attachment = FileAttachment::find($attachment_id);
            $attachment->item_id = $item_id;
            $attachment->item_type = $item_type;
            $attachment->save();
        });
    }
    
    /**
     * 根据文件的路径找到附件
     * 
     * @param string $file_path
	 * 
	 * @return FileAttachment
     */
    public static function findAttachmentByFilePath($file_path) {
        $attachment = FileAttachment::where('src', $file_path)->first();
        if ($attachment) {
            return $attachment;
        } else {
            return "";
        }
    }
    
    /**
     * 根据item的信息找到附件
     * 
     * @param int $item_id
     * @param string $item_type
	 * 
	 * @return FileAttachment
     */
    public static function findAttachmentByItem($item_id, $item_type) {
        $attachment = FileAttachment::where('item_id', $item_id)->where('item_type', $item_type)->first();
        if ($attachment) {
            return $attachment;
        } else {
            return "";
        }
    }
}
